import HTTP_METHOD from './http-method'
import { message } from 'antd'

async function errHandler (res) {
  const body = await res.json()
  message.error(body.message)
  return {status: res.status}
}

export const get = async (url) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.GET,
      credentials: 'include',
      headers: new Headers({
        'Accept': 'application/json;charset=utf-8',
        'id': 21,
        'userName': 'aaa',
        'roles': [1, 2, 9]
      })
    })

    if (!res.ok) {
      return errHandler(res)
    }
    const body = await res.json()
    const status = res.status

    return Object.assign({}, {body}, {status})
  } catch (ex) {
    // alert(ex)
    return {status: ex.status}
  }
}

export const del = async (url) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.DELETE,
      credentials: 'include',
      headers: new Headers({
        'Accept': 'application/json;charset=utf-8',
        'id': 21,
        'userName': 'aaa',
        'roles': [1, 2, 9]
      })
    })
    return {status: res.status}
  } catch (ex) {
    // alert(ex)
    return {status: ex.status}
  }
}

export const post = async (url, data) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.POST,
      session: {'uuid': 'SW3hF4l1oh9JXbNqTRSw2dfMA-RI4KNG', 'cookie': {'originalMaxAge': null, 'expires': null, 'httpOnly': true, 'path': '/'}, 'user': {'id': 5, 'username': 'admin', 'roles': ['9']}},
      credentials: 'include',
      headers: new Headers({
        'session': {
          '_id': 'SW3hF4l1oh9JXbNqTRSw2dfMA-RI4KNG',
          'session': {'cookie': {'originalMaxAge': null, 'expires': null, 'httpOnly': true, 'path': '/'}, 'user': {'id': 5, 'username': 'admin', 'roles': ['9']}},
          'expires': '12/5/17 10:24:33 AM UTC'
        },
        'Content-Type': 'application/json;charset=utf-8',
        'Accept': 'application/json',
        'id': 21,
        'userName': 'aaa',
        'roles': [1, 2, 9]
      }),
      body: JSON.stringify(data)
    })
    if (!res.ok) {
      return errHandler(res)
    }
    const body = await res.json()
    const status = res.status

    return Object.assign({}, {body}, {status})
  } catch (ex) {
    alert(ex)
    return {status: ex.status}
  }
}

export const update = async (url, data) => {
  try {
    const res = await fetch(url, {
      method: HTTP_METHOD.PUT,
      credentials: 'include',
      headers: new Headers({
        'Content-Type': 'application/json;charset=utf-8',
        'Accept': 'application/json',
        'id': 21,
        'userName': 'aaa',
        'roles': [1, 2, 9]
      }),
      body: JSON.stringify(data)
    })

    if (!res.ok) {
      return errHandler(res)
    }
    return {status: res.status}
  } catch (ex) {
    alert(ex)
    return {status: ex.status}
  }
}
